<template>
  <div class="calendar_box">
    <div class="calendar_month months">
      <span
        v-for="(item, index) in batchYear"
        :key="index"
        :class="index === yearindex ? 'year' : 'year1'"
        @click="batchChange(item, index)"
      >{{ item + "年" }}</span>
    </div>

    <div class="calendar_month month">
      <span
        v-for="(item, index) in batchMonth"
        :key="index"
        :class="index === MonthIndex ? 'year' : 'year1'"
        @click="batchMonthChange({ y: currentYear, m: item - 1 }, index)"
      >{{ item + "月" }}</span>
    </div>
    <div class="calendar_month">
      <i
        v-if="
          startYearMonth === currentYear + '-' + currentMonth ? false : true
        "
        class="cs-chevronleft el-icon-d-arrow-left"
        @click="pre()"
      ></i>
      <i
        v-if="
          startYearMonth === currentYear + '-' + currentMonth ? true : false
        "
        class="cs-chevronleft"
      ></i>
      <span>{{ currentYear + "年" + currentMonth + "月" }}</span>
      <i
        v-if="endYearMonth === currentYear + '-' + currentMonth ? false : true"
        class="cs-chevronright el-icon-d-arrow-right"
        @click="next()"
      ></i>
      <i
        v-if="endYearMonth === currentYear + '-' + currentMonth ? true : false"
        class="cs-chevronright"
      ></i>
    </div>
    <div class="calendar_week">
      <div class="cal-cell1">周日</div>
      <div class="cal-cell1">周一</div>
      <div class="cal-cell1">周二</div>
      <div class="cal-cell1">周三</div>
      <div class="cal-cell1">周四</div>
      <div class="cal-cell1">周五</div>
      <div class="cal-cell1">周六</div>
    </div>
    <div class="calendar_days">
      <div v-for="(day, index) in days" :key="index" class="calendar_week_days">
        <div
          v-for="(item, idx) in day"
          :key="idx"
          :class="(idx+2*2.64) * (index+24*.4) === dayidx ? 'month_day' : ''"
          class="cal_month_day"
        >
          <div
            class="events_list"
            :class="titleColor(events[item.value])"
            :title="title(events[item.value], item.value)"
            @click.stop="evenday(item.value, events[item.value], (idx+2*2.64) * (index+24*.4))"
          >
            <span
              :class="{
                disabled: item.disabled,
                red: idx === 0 || idx === 6,
                active: currentDayValue === item.value
              }"
            >{{ item.day }}</span>
            <!-- <el-tooltip
              v-for="(ev, i) in events[item.value]"
              :key="i"
              placement="top"
              :content="ev"
            >-->
            <!-- <div>{{ ev.title }}</div> -->
            <!-- <div>456</div> -->
            <!-- <router-link
                :to="toEventDetail(ev)"
                class="dot"
                :class="{
                  'gray': parseInt(item.value) < parseInt(currentDayValue)
                }"
            />-->
            <!-- </el-tooltip> -->
          </div>
          <!-- <el-tooltip content="Top center" placement="top">
  <el-button>{{item.value}}</el-button>
          </el-tooltip>-->
          <!-- <div class="events_list">
            <el-tooltip placement="top" content="ssx">
              <router-link
                :to="toEventDetail(ev)"
                class="dot"
                :class="{
                  'gray': parseInt(item.value) < parseInt(currentDayValue)
                }"
              />
            </el-tooltip>
          </div>-->
        </div>
      </div>
    </div>

    <div v-for="(item, index) in farmingtList" :key="index">
      <span>{{ item.agriculturalWorkTypeName }}</span>
    </div>
    <div v-for="(item, index) in percentList" :key="index + 100">
      <span>{{ item.agriculturalMaterialName }}</span>
    </div>
  </div>
</template>
<script>
//   import { getCalendarEventsApi } from '@/apis'
import EventsApi from "@/api/trace-source-web/production-api/index-primary.js";

export default {
  props: {
    batId: {
      type: [String, Number],
      default: () => ""
    },
    batchTime: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      currentDayValue: 0,
      currentMonth: 1,
      currentYear: 2021,
      batchMonth: [],
      batchYear: [],
      startYearMonth: "",
      endYearMonth: "",
      days: [], // 日历数据
      events: {
        // "20220406": [
        //   { datemes1: "456",
        //     datemes2: "456",
        //     datemes3: "456",
        //     title: '喵喵1' }batchMonth
        // ]
      }, // 活动数据
      params: {}, // 活动查询参数
      farmingtList: [],
      percentList: [],
      yearindex: 0,
      MonthIndex: 0,
      dayidx: null
    };
  },
  watch: {
    batchTime: {
      deep: true,
      handler(val) {
        // console.log(val)
        this.initTime();
        // console.log(this.batId)
      }
    }
    // batId: {
    //   handler(val) {
    //     this.initTime();
    //   }
    // }
  },
  mounted() {
    this.$nextTick(() => {
      this.initTime();
    });
    // this.initDate()
    // let _now = new Date()
    // this.currentYear = _now.getFullYear()
    // this.currentMonth = _now.getMonth() + 1
    // let d = _now.getDate()
    // console.log(d, "d")
    // this.currentDayValue = this.formatValue(this.currentYear, this.currentMonth, d)
  },
  methods: {
    // 边框 字体颜色切换
    titleColor(val) {
      // console.log(val)
      if (val !== undefined) {
        // console.log(val)
        if (val.hasAgriculturalInput) {
          return "events";
        } else if (val.hasFarmingOperation) {
          return "events";
        } else {
          return "events";
        }
      }
    },
    // 鼠标 提示
    title(val, e) {
      if (val !== undefined) {
        // console.log(val)
        if (val.hasAgriculturalInput) {
          return "点击查看农资投入信息";
        } else if (val.hasFarmingOperation) {
          return "点击查看农事作业信息";
        } else {
          return "点击查看农资，农事信息";
        }
      }
    },
    // 点击每天值
    evenday(e, events, dayidx) {
      if (events === undefined) {
        events = null;
      }
      this.dayidx = dayidx;
      // console.log(dayidx)
      this.$emit("evenday", {
        e: e.slice(0, 4) + "-" + e.slice(4, 6) + "-" + e.slice(6, 8),
        events: events
      });
    },
    // 获取年月区间
    initTime() {
      // 获取父组件的批次开始日期，结束日期
      this.batchYear = [];
      if (this.batchTime.length > 0) {
        this.batchTime.forEach(item => {
          this.batchYear.push(item.slice(0, 4));
        });
        // 去重
        this.batchYear = this.indexOfUniq(this.batchYear);
        let timeline = this.batchYear.slice(-1)[0];
        this.$nextTick(() => {
          this.batchChange(timeline, this.batchYear.length - 1);
        });
      }
    },
    // 年份切换
    batchChange(val, index) {
      // 获取点击的年份
      // console.log(val)
      this.currentYear = parseInt(val);
      this.dayidx = null;
      // 年份样式切换
      this.yearindex = index;
      this.batchMonth = [];
      this.batchTime.forEach(item => {
        if (val === item.slice(0, 4)) {
          item = item.slice(5, 8);
          this.batchMonth.push(item);
        }
      });
      // 去重
      this.batchMonth = this.indexOfUniq(this.batchMonth);
      // 默认展示 结束月份
      this.currentMonth = parseInt(this.batchMonth.slice(-1)[0]);
      // 获取开始年月
      // console.log(this.batchMonth.slice(0)[0])
      // console.log(this.batchMonth.slice(0)[0], this.batchMonth.slice(0))
      this.startYearMonth =
        this.batchYear[0] + "-" + parseInt(this.batchMonth.slice(0)[0]);
      // 获取结束年月
      this.endYearMonth =
        this.batchYear.slice(-1)[0] +
        "-" +
        parseInt(this.batchMonth.slice(-1)[0]);
      // 默认展示月份
      this.currentYear = parseInt(val);
      this.MonthIndex = this.batchMonth.length - 1;

      this.$nextTick(() => {
        // 向父组件传输点击的年份
        this.$emit("evenYear", { se: "Year", date: this.currentYear });
        // 日历转化
        this.initDate({ y: this.currentYear, m: this.currentMonth - 1 });
      });
    },
    // 月份年份切换
    batchMoChange(val, index) {
      // 获取点击的年份
      // console.log(val)
      this.currentYear = parseInt(val);
      this.dayidx = null;
      // 年份样式切换
      this.yearindex = index;
      this.batchMonth = [];
      this.batchTime.forEach(item => {
        if (val === item.slice(0, 4)) {
          item = item.slice(5, 8);
          this.batchMonth.push(item);
        }
      });
      // 去重
      this.batchMonth = this.indexOfUniq(this.batchMonth);
      // 获取每个年份的 开始 月份
      this.startYearMonth =
        this.batchYear[0] + "-" + parseInt(this.batchMonth.slice(0)[0]);
      // // 获取每个年份的 开始 月份
      this.endYearMonth =
        this.batchYear.slice(-1)[0] +
        "-" +
        parseInt(this.batchMonth.slice(-1)[0]);
    },
    batchMonthChange(val, index) {
      this.MonthIndex = index;
      this.dayidx = null;
      this.currentMonth = val.m + 1;
      let m = val.m + 1;
      if (m < 10) {
        m = "0" + m;
      }
      // console.log(val.y + "-" + m)
      // 向父组件传输点击的月份份
      this.$emit("evenYear", { se: "Month", date: val.y + "-" + m });
      this.$nextTick(() => {
        // 日历转化
        this.initDate(val);
      });
    },
    // 去重
    indexOfUniq(arr) {
      let result = [];
      for (let i = 0, len = arr.length; i < len; i++) {
        // 用indexOf 简化了二层循环的流程
        if (result.indexOf(arr[i]) === -1) result.push(arr[i]);
      }
      return result;
    },
    // 初始化日期（ 显示日历的主要原因）
    initDate(datoObj) {
      let now = !datoObj ? new Date() : new Date(datoObj.y, datoObj.m, 1);
      // 获取当前时间
      let y = now.getFullYear();
      let m = now.getMonth();
      // console.log(datoObj)

      // let d = now.getDate()
      // 当月最后一天是几号
      let _lastDateOfMonth = new Date(y, m + 1, 0).getDate();
      // 当月第一天是周几
      let _firstDayWeekOfMonth = new Date(y, m, 1).getDay();
      // 上月最后一天是几号
      let _lastDayOfLastMonth = new Date(y, m, 0).getDate();

      let line = 0;
      let temp = [];
      let start = null;
      let end = null;
      for (let i = 1; i <= _lastDateOfMonth; i++) {
        let _day = new Date(y, m, i).getDay(); // 返回星期几
        // 第一行
        if (_day === 0) {
          temp[line] = [];
          // 如果当月第一天就是周天，取查询参数值
          if (_firstDayWeekOfMonth === 0) {
            start = this.formatValuetwo(y, m + 1, 1);
          }
          // console.log(start)
        } else if (i === 1) {
          let k = 0;
          temp[line] = [];
          k = _lastDayOfLastMonth - _firstDayWeekOfMonth + 1;
          for (let j = 0; j < _firstDayWeekOfMonth; j++) {
            // 取查询参数值
            if (j === 0) {
              start = this.formatValuetwo(y, m, k);
              // console.log(start)
            }
            temp[line].push({
              day: k,
              disabled: true,
              value: this.formatValue(y, m, k)
            });
            k++;
          }
        }

        temp[line].push({
          day: i,
          value: this.formatValue(y, m + 1, i)
        });

        // 到周六，并且行数小于5时换行
        if (_day === 6 && line < 5) {
          line++;
          temp[line] = [];
        }
        // 如果到了当月最后一天
        if (i === _lastDateOfMonth) {
          // 下个月的时间补位
          let next = 1;
          let max = line === 5 ? 6 : 13;
          let d = _day;
          // 当最后一天是周六的时候，说明没占位，下个月占位需要为7位
          // 当最后一天不是周六的时候，说明占位了，那么下个月占位需要减1位
          if (_day === 6) {
            d = 0;
            max = 7;
          }
          for (; d < max; d++) {
            // 如果为周六，且行数小于5时候
            if (d === 6 && line < 5) {
              line++;
              temp[line] = [];
            }
            // 取查询参数值
            if (d === max - 1) {
              end = this.formatValuetwo(y, m + 2, next);
            }
            temp[line].push({
              day: next,
              disabled: true,
              value: this.formatValue(y, m + 2, next)
            });
            next++;
          }
        }
      }
      let params = {
        batchNo: this.batId,
        startDate: start,
        endDate: end
      };
      this.days = temp;
      // console.log(this.days)
      EventsApi.getCalendarEventsApi(params).then(res => {
        if (res.code === 1) {
          // console.log(res.data)
          if (res.data === undefined) {
            this.events = {};
          } else {
            this.events = res.data;
          }
        }
      });
    },
    formatValue(y, m, d) {
      if (m > 12) {
        y += 1;
        m = 1;
      } else if (m < 1) {
        y -= 1;
        m = 12;
      }
      let _m = m > 9 ? m : "0" + m;
      let _d = d > 9 ? d : "0" + d;
      return y.toString() + _m + _d;
    },
    formatValuetwo(y, m, d) {
      if (m > 12) {
        y += 1;
        m = 1;
      } else if (m < 1) {
        y -= 1;
        m = 12;
      }
      let _m = m > 9 ? m : "0" + m;
      let _d = d > 9 ? d : "0" + d;
      return y.toString() + "-" + _m + "-" + _d;
    },
    // 向前（月份向前）
    pre() {
      this.currentMonth -= 1;
      if (this.currentMonth < 1) {
        this.currentMonth = 12;
        this.currentYear -= 1;
      }
      // console.log(e, x)
      this.initDate({ y: this.currentYear, m: this.currentMonth - 1 });
      // 判断向前的年份 样式
      if (
        this.batchYear.length - 1 >= this.yearindex &&
        this.yearindex > 0 &&
        this.currentMonth === 12
      ) {
        this.yearindex--;
      } else {
        this.yearindex === 0;
      }
      this.batchMoChange(this.batchYear[this.yearindex], this.yearindex);
      let Month = this.currentMonth;
      // 重置选中样式
      this.dayidx = null;

      if (this.currentMonth < 10) {
        Month = "0" + this.currentMonth;
      }
      // 判断 月份index < 总月份长度 index +1
      if (
        this.batchMonth.length - 1 >= this.MonthIndex &&
        this.MonthIndex > 0
      ) {
        this.MonthIndex--;
      } else {
        this.MonthIndex = this.batchMonth.length - 1;
        // console.log('向前' + this.MonthIndex, this.batchMonth.length - 1, this.batchMonth)
      }
      // console.log('向前' + this.MonthIndex)
      this.$emit("evenYear", {
        se: "Month",
        date: this.currentYear + "-" + Month
      });
    },
    // 向后（月份向后）
    next() {
      this.currentMonth += 1;
      if (this.currentMonth > 12) {
        this.currentMonth = 1;
        this.currentYear += 1;
      }
      this.initDate({ y: this.currentYear, m: this.currentMonth - 1 });
      // 判断向后的年份
      if (
        this.yearindex >= 0 &&
        this.batchYear.length - 1 >= this.yearindex &&
        this.currentMonth === 1
      ) {
        this.yearindex++;
      } else {
        this.yearindex === this.batchYear.length - 1;
      }
      // 年份过渡
      this.batchMoChange(this.batchYear[this.yearindex], this.yearindex);
      let Month = this.currentMonth;
      if (this.currentMonth < 10) {
        Month = "0" + this.currentMonth;
      }
      // 重置选中样式
      this.dayidx = null;
      // 判断向后的月份
      if (
        this.MonthIndex >= 0 &&
        this.batchMonth.length - 1 >= this.MonthIndex
      ) {
        this.MonthIndex++;
      } else {
        this.MonthIndex = 0;
      }
      // console.log('向后' + this.MonthIndex)
      this.$emit("evenYear", {
        se: "Month",
        date: this.currentYear + "-" + Month
      });
    },
    toEventDetail(item) {
      let _route =
        item.productIds && item.productIds.length > 0
          ? `/event/sale/${item.id}`
          : `/event/${item.id}`;
      if (item.id === 76) {
        _route = "/dtc";
      }
      return _route;
    }
  }
};
</script>
<style lang="scss" scoped>
.calendar_box {
  // margin-left:20px;
  // width:230px;
  width: 100%;
  box-shadow: 0 0 12px 0 rgba(0, 0, 0, 0.05);
  font-family: -apple-system, "Helvetica Neue", Helvetica, Arial, "PingFang SC",
    "Hiragino Sans GB", "WenQuanYi Micro Hei", "Microsoft Yahei", sans-serif;
  font-size: 14px;
  color: #fffff0;
  background-color: #fffff040;
  -webkit-font-smoothing: antialiased;
}
.calendar_month {
  border: 1px solid #fffff040;
  height: 49px;
  line-height: 49px;
  font-size: 18px;
  font-weight: 700;
  display: flex;
  justify-content: space-around;
  span {
    margin: 0 30px;
    vertical-align: middle;
  }
  i {
    cursor: pointer;
    vertical-align: middle;
    font-size: 24px;
    white-space: nowrap;
    width: 34px;
    line-height: 45px;
    display: inline-block;
  }
}
.month {
  width: 100%;
  overflow-x: auto;
  text-align: start;
  display: inline-block;
  cursor: pointer;
  height: 100%;
  .year {
    border: 1px solid #00d9ff;
    padding: 5px 10px;
    border-radius: 15px;
    color: #00d9ff;
    cursor: pointer;
  }
  .month {
    border: 1px solid #00d9ff;
    padding: 5px 10px;
    border-radius: 15px;
    color: #00d9ff;
  }
  span {
    margin: 0 3px 0;
    padding: 5px 8px;
    border: 1px solid #21b8d300;
    transition: 1s;
    &:hover {
      border: 1px solid #00d9ff;
      padding: 5px 10px;
      border-radius: 15px;
      color: #00d9ff;
    }
  }
}
.months {
  width: 100%;
  overflow-x: auto;
  text-align: center;
  display: inline-block;
  cursor: pointer;
  height: 100%;
  .year {
    border: 1px solid #00d9ff;
    padding: 5px 10px;
    border-radius: 15px;
    color: #00d9ff;
    cursor: pointer;
  }
  .month {
    border: 1px solid #00d9ff;
    padding: 5px 10px;
    border-radius: 15px;
    color: #00d9ff;
  }
  span {
    margin: 0 3px 0;
    padding: 5px 8px;
    border: 1px solid #21b8d300;
    transition: 1s;

    &:hover {
      border: 1px solid #00d9ff;
      padding: 5px 10px;
      border-radius: 15px;
      color: #00d9ff;
    }
  }
}
.calendar_week {
  display: flex;
  border: 1px solid #fffff040;
  padding: 5px 0;
  margin: 1px 0;
  .cal-cell1 {
    flex: 1;
    font-weight: bolder;
    text-align: center;
  }
}
.calendar_week_days {
  display: flex;
  border-right: 1px solid #fffff040;
  .cal_month_day {
    flex: 1;
    height: 60px;
    text-align: center;
    border-left: 1px solid #fffff040;
    border-bottom: 1px solid #fffff040;
    cursor: pointer;
    span {
      display: inline-block;
      font-size: 20px;
      line-height: 30px;
      transition: all 0.3s ease-in-out;
      -webkit-transition: all 0.1s ease-in-out;
      &.disabled {
        opacity: 0.25;
      }
      &.red {
        color: #e8fde7;
      }
      &.active {
        width: 30px height 30px border-radius 50% background-color #e8fde7 color
          darkgreen;
      }
    }
  }
  .month_day {
    .events_list {
      padding: 13px;
      height: 100%;
      border: 2px solid #7ed32100;
      overflow: hidden;
      transition: 0.5s;
      // margin: 10px;
      border: 2px solid #00d9ff !important;
      background-color: #00d9ff;
      box-sizing: border-box;
      // border-radius: 45px;
      color: #fffff0 !important;
      box-shadow: 0px 0px 5px #000000;
      .red {
        color: #fffff0 !important;
      }
      span {
        color: #fffff0 !important;
      }
      .dot {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        // background-color: #7ed321;
        margin: 0 1px;
        &.gray {
          background-color: #666666;
        }
      }
    }
  }
}
.events {
  // padding: 2px !important;
  padding: 13px;
  // margin: 10px;
  border: 2px solid #84ff00 !important;
  // border-radius: 45px;
  //
  // background: #36d321;
  // color: #7ed321 !important;
  box-shadow: inset 0px 0px 4px #55a00490;

  span {
    // display: inline-block;
    // height: 100%;
    // width: 100%;
    // border: 2px solid #84ff00 !important;
    // padding: 9px;
    // border-radius: 45px;
    // box-shadow: inset 0px 0px 10px #55a00490;
    // text-shadow: inset 0px 0px 10px #00000090;
    color: #84ff00 !important;
  }
  // .red {
  //   border: 2px solid #55a004 !important;
  //   border-radius: 45px;
  //   display: inline-block;
  //   color: #7ed321 !important;
  // }
}
.eventas {
  padding: 13px;
  // margin: 10px;
  border: 2px solid #00d9ff !important;
  border-radius: 45px;
  color: #00d9ff !important;
  .red {
    color: #00d9ff !important;
  }
}
.evenkas {
  padding: 13px;
  // margin: 10px;
  border: 2px solid #bbd321 !important;
  border-radius: 45px;
  color: #bbd321 !important;
  .red {
    color: #bbd321 !important;
  }
}
.events_list {
  padding: 13px;
  height: 100%;
  border: 2px solid #7ed32100;
  overflow: hidden;
  transition: 0.5s;
  &:hover {
    // margin: 10px;
    border: 2px solid #00d9ff !important;
    border-radius: 45px;
    background-color: #00d9ff00 !important;
    // color: #00d9ff !important;
    // .red {
    //   color: #00d9ff !important;
    // }
  }
  .dot {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #7ed321;
    margin: 0 1px;
    &.gray {
      background-color: #666666;
    }
  }
}
</style>
